import { Op } from 'sequelize';
import JobLog from '@/models/monitor/job-log.model';
import { getLogger } from '@/utils/logger';

// 创建常规日志记录器（不输出到控制台）
const logger = getLogger('joblog-service', {
  console: false
});
// 创建控制台日志记录器
const consoleLogger = getLogger('joblog-service');

/**
 * 定时任务日志服务类
 */
class JobLogService {
  /**
   * 查询定时任务日志列表（分页+筛选）
   * @param query 查询参数
   * @returns 日志分页列表
   */
  public async selectJobLogList(query: any): Promise<{ rows: any[]; total: number }> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`查询任务日志列表: ${JSON.stringify(query)}`);
      
      const { jobName, jobGroup, status, params = {}, pageNum = 1, pageSize = 10 } = query;
      const where: any = {};
      
      if (jobName) where.jobName = { [Op.like]: `%${jobName}%` };
      if (jobGroup) where.jobGroup = jobGroup;
      if (status) where.status = status;
      if (params.beginTime && params.endTime) {
        where.createTime = { [Op.between]: [params.beginTime, params.endTime] };
      } else if (params.beginTime) {
        where.createTime = { [Op.gte]: params.beginTime };
      } else if (params.endTime) {
        where.createTime = { [Op.lte]: params.endTime };
      }
      
      const offset = (pageNum - 1) * pageSize;
      const limit = pageSize;
      
      const { rows, count } = await JobLog.findAndCountAll({
        where,
        order: [['createTime', 'DESC']],
        offset,
        limit
      });
      
      // 记录查询结果
      logger.info(`任务日志列表查询完成: 总数=${count}, 当前页=${pageNum}, 每页大小=${pageSize}`);
      
      return { rows, total: count };
    } catch (error) {
      consoleLogger.error(`查询任务日志列表失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('查询任务日志列表失败');
    }
  }

  /**
   * 批量删除定时任务日志
   * @param jobLogIds 日志ID数组
   * @returns 删除数量
   */
  public async deleteJobLogByIds(jobLogIds: number[]): Promise<number> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`批量删除任务日志: jobLogIds=${JSON.stringify(jobLogIds)}`);
      
      const result = await JobLog.destroy({ where: { jobLogId: jobLogIds } });
      
      // 记录操作结果
      logger.info(`任务日志批量删除完成: 删除数量=${result}, 请求删除数量=${jobLogIds.length}`);
      
      return result;
    } catch (error) {
      consoleLogger.error(`批量删除任务日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('批量删除任务日志失败');
    }
  }

  /**
   * 清空定时任务日志
   * @returns 删除数量
   */
  public async cleanJobLog(): Promise<number> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info('清空任务日志');
      
      const result = await JobLog.destroy({ where: {} });
      
      // 记录操作结果
      logger.info(`任务日志清空完成: 删除数量=${result}`);
      
      return result;
    } catch (error) {
      consoleLogger.error(`清空任务日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('清空任务日志失败');
    }
  }

  /**
   * 查询定时任务日志详情
   * @param jobLogId 日志ID
   * @returns 日志详情
   */
  public async selectJobLogById(jobLogId: number): Promise<any> {
    try {
      // 使用consoleLogger记录操作开始
      consoleLogger.info(`根据ID查询任务日志: jobLogId=${jobLogId}`);
      
      const jobLog = await JobLog.findByPk(jobLogId);
      
      if (!jobLog) {
        logger.info(`未找到任务日志: jobLogId=${jobLogId}`);
        return null;
      }
      
      // 记录查询结果
      logger.info(`任务日志查询成功: jobLogId=${jobLogId}, jobName=${jobLog.jobName}`);
      
      return jobLog;
    } catch (error) {
      consoleLogger.error(`根据ID查询任务日志失败: ${error instanceof Error ? error.message : String(error)}`);
      throw new Error('查询任务日志详情失败');
    }
  }
}

export default new JobLogService(); 